from django.shortcuts import render,redirect
from django.views import View

from app0423 import models
from app0423.models import Department


# Create your views here.
def depart_list(request):
    queryset = models.Department.objects.all()
    return render(request,'depart_list.html',{'queryset':queryset})

def depart_add(request):
    if request.method == 'GET':
        return render(request,'depart_add.html')
    
    title = request.POST.get('title')
    
    models.Department.objects.create(title=title)
    
    return redirect("/depart/list")

def depart_delete(request):
    id = request.GET.get('nid')
    models.Department.objects.filter(id=id).delete()
    return redirect("/depart/list")


def depart_edit(request, nid):
    if request.method == "GET":
        queryset = models.Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {'queryset': queryset})

    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect("/depart/list")

def user_list(request):
    queryset = models.UserInfo.objects.all()
    return render(request,'user_list.html',{'queryset':queryset})

def user_add(request):
    context = {"depart_list": models.Department.objects.all()}
    return render(request,"user_add.html",context)



from django import forms
class UserModelForm(forms.ModelForm):

    name = forms.CharField(min_length=3,max_length=20)
    password = forms.CharField(min_length=8,max_length=20)


    class Meta:
        model = models.UserInfo
        fields = ["name","password","age","salary","gender","department"]
        # widgets = {
        #     "name":forms.TextInput(attrs={"class":"form-control"}),
        #     "password":forms.PasswordInput(attrs={"class":"form-control"}),
        #     "age":forms.NumberInput(attrs={"class":"form-control"}),
        #     "gender":forms.RadioSelect(attrs={"class":"form-control"}),
        #     "department":forms.Select(attrs={"class":"form-control"})
        #
        # }
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        for name,field in self.fields.items():
            field.widget.attrs.update({"class":"form-control","placeholder":field.label})


def user_model_form_add(request):
    if request.method == "GET":
        form = UserModelForm()
        return render(request,"user_model_form_add.html",{'form':form})

    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list")
    else:
        print(form.errors)
        return render(request,"user_model_form_add.html",{'form':form})



